/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.riversoft.weixin.gateway.service;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 *
 * @author johns
 */
@Service
public class RedisServiceImpl implements RedisService {

    private Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);
    @Autowired
    RedisTemplate redisTemplate;

    /**
     *  redis 锁
     * @param lock 锁的key
     * @param expire 锁的时长
     * @return
     */
    @Override
    public Boolean redisLock(final String lock, final int expire) {

        return (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                boolean locked = false;
                byte[] lockKeyName = redisTemplate.getStringSerializer().serialize(lock);
                byte[] lockValue = redisTemplate.getValueSerializer().serialize(getDateAferExpire(expire));
                locked = connection.setNX(lockKeyName, lockValue);
                if (locked){
                    connection.expire(lockKeyName, TimeoutUtils.toSeconds(expire, TimeUnit.MILLISECONDS));
                }
                return locked;
            }
        });
    }
    /**
     *
     * 判断key是否存在
     *
     * @param key
     */
    @Override
    public boolean existsKey(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取指定时长后的Date
     * @param expireTime
     * @return
     */
    @Override
    public Date getDateAferExpire(int expireTime){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND, expireTime);
        return calendar.getTime();
    }

    /**
     * 根据key 获取对应的value
     *
     * @param key
     */
    @Override
    public Object getValueByKey(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 删除指定的key
     *
     * @param key
     */
    @Override
    public void removeByKey(final String key) {
        if (existsKey(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 设置带有指定时长的key value
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    @Override
    public boolean setKeyValueWithExpire(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            if (expireTime != null) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
